package com.acooly.module.openapi.client.provider.shengpay;

import com.acooly.module.openapi.client.api.notify.ApiServiceClientServlet;
import com.acooly.module.openapi.client.api.transport.HttpTransport;
import com.acooly.module.openapi.client.api.transport.Transport;
import com.acooly.module.openapi.client.provider.shengpay.notify.ShengpayApiServiceClientServlet;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import java.util.List;


@EnableConfigurationProperties({OpenAPIClientShengpayProperties.class})
@ConditionalOnProperty(value = OpenAPIClientShengpayProperties.PREFIX + ".enable", matchIfMissing = true)
@ComponentScan
@ComponentScan("com.acooly.module.openapi.client.file")
public class OpenAPIClientShengpayConfigration {

    @Autowired
    private OpenAPIClientShengpayProperties openAPIClientYipayProperties;

    @Bean("shengpayHttpTransport")
    public Transport shengpayHttpTransport() {
        HttpTransport httpTransport = new HttpTransport();
        httpTransport.setGateway(openAPIClientYipayProperties.getGatewayUrl());
        httpTransport.setConnTimeout(String.valueOf(openAPIClientYipayProperties.getConnTimeout()));
        httpTransport.setReadTimeout(String.valueOf(openAPIClientYipayProperties.getReadTimeout()));
        return httpTransport;
    }

    /**
     * 接受异步通知的filter
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean shengpayClientServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        ShengpayApiServiceClientServlet apiServiceClientServlet = new ShengpayApiServiceClientServlet();
        bean.setServlet(apiServiceClientServlet);
        bean.addInitParameter(ApiServiceClientServlet.NOTIFY_DISPATCHER_BEAN_NAME_KEY, "shengpayNotifyHandlerDispatcher");
        List<String> urlMappings = Lists.newArrayList();       //网关异步通知地址
        urlMappings.add(ShengpayConstants.getCanonicalUrl(openAPIClientYipayProperties.getNotifyUrl(), "/*"));//访问，可以添加多个
        bean.setUrlMappings(urlMappings);
        bean.setLoadOnStartup(3);
        return bean;
    }
}
